package com.wenyl.linear.queue;

import lombok.Data;


/**
 * @author Swimming Dragon
 * @description: 数组实现循环队列，留出一个空位判断队满
 * @date 2024年10月18日 11:52
 */
@Data
public class ArrayQueue {
    private final int[] elements;
    // 队头元素下标
    private int front;
    // 队尾元素下标
    private int rear;
    public static final int MAX_SIZE = 10;
    public ArrayQueue(){
        elements = new int[MAX_SIZE];
        rear = front = 0;
    }

    /**
     * 数据在队尾入队
     * @param data 数据
     */
    public void offer(int data){
        if(isFull()){
            System.out.println("队满");
            return;
        }
        elements[rear] = data;
        rear = (rear + 1) % MAX_SIZE;
    }

    /**
     * 空队返回-1
     * @return 队首数据出队
     */
    public int poll(){
        if(isEmpty()){
            System.out.println("空队");
            return -1;
        }
        int ret = elements[front];
        front = (front +1) % MAX_SIZE;
        return ret;
    }
    public boolean isEmpty(){
        return front == rear;
    }
    // 数组流出一个空闲位置
    public boolean isFull(){
        return (rear+1)%MAX_SIZE == front;
    }

    public void print() {
        if(isEmpty()){
            System.out.println("空队遍历");
            return;
        }
        for(int index = front;index < rear;index++){
            System.out.print(elements[index]+" ");
        }
        System.out.println();
    }
}


